import sys
from PyQt5.QtWidgets import QApplication, QFileDialog
from ui.main_window import SheepDetectorUI
from utils.detection_thread import DetectionThread
from model.yolov8_model import YOLONet
from config.settings import IMAGE_FILTER, MODEL_FILTER


class AppController:
    def __init__(self):
        self.app = QApplication(sys.argv)
        self.ui = SheepDetectorUI()
        self.model = YOLONet()
        self.images = []
        self.current_image = ""

    def show_window(self):
        self.ui.show()
        sys.exit(self.app.exec_())

    # 模型加载逻辑
    def load_model(self):
        path, _ = QFileDialog.getOpenFileName(
            self.ui, "选择模型", "", MODEL_FILTER
        )
        if path:
            success, msg = self.model.load_model(path)
            if success:
                self.ui.show_model_path(path)
                self.enable_detect_button()
            else:
                self.ui.show_warning(msg)

    # 图片导入逻辑
    def import_images(self):
        paths, _ = QFileDialog.getOpenFileNames(
            self.ui, "导入图片", "", IMAGE_FILTER
        )
        if paths:
            self.images.extend(paths)
            self.ui.show_image_list(self.images)
            self.enable_detect_button()

    # 检测逻辑
    def detect(self):
        if not self.current_image:
            self.ui.show_warning("请选择图片")
            return

        conf = self.ui.conf_spin.value()
        iou = self.ui.iou_spin.value()
        self.thread = DetectionThread(
            self.model.model.path, self.current_image, conf, iou
        )
        self.thread.finished.connect(self.on_detection_finished)
        self.thread.start()

    # 结果处理逻辑
    def on_detection_finished(self, image, count, metrics):
        if image is None:
            self.ui.show_warning(metrics.get("error", "检测失败"))
            return

        # 这里调用图片显示逻辑（需在UI类中实现）
        self.ui.show_image_display(image)
        self.ui.show_count(count)
        self.ui.show_metrics(metrics)


if __name__ == "__main__":
    controller = AppController()
    controller.show_window()